<template>
  <div>
    <el-tabs v-model="model.activeName" class="demo-tabs">
      <el-tab-pane name="1" label="评审记录">
        <el-button
          class="btnClass"
          v-if="!editStatus"
          @click="addReview"
          type="primary"
          >添加评审记录</el-button
        >
        <el-row
          v-for="(item, index) in model.dataList"
          :key="index"
          style="margin-bottom: 20px"
        >
          <el-col class="milepost-box" :xl="16" :lg="24">
            <div class="milepost-title">
              评审记录{{ index + 1 }}
              <el-popconfirm
                v-if="!editStatus"
                confirm-button-text="确定"
                cancel-button-text="取消"
                icon="el-icon-info"
                icon-color="red"
                title="确定删除该条记录吗？"
                @confirm="delForList(index)"
              >
                <template #reference>
                  <i class="close el-icon-delete" />
                </template>
              </el-popconfirm>

              <i
                v-if="!editStatus"
                class="save el-icon-collection"
                @click="saveReview(index)"
              />
            </div>
            <el-row>
              <el-col :span="20">
                <el-form
                  :ref="el => (reviewForm[index] = el)"
                  :rules="reviewFormRules"
                  label-width="140px"
                  :model="item"
                >
                  <el-form-item label="主题" prop="title">
                    <el-input :disabled="editStatus" v-model="item.title" />
                  </el-form-item>
                  <el-form-item label="参评人" prop="participant">
                    <SelectForTable
                      :disabled="editStatus"
                      :ref="el => (selectTable[index] = el)"
                      @change="changeParticipant($event, index)"
                      :value="item.participantList"
                    />
                  </el-form-item>

                  <el-form-item label="会议时间" prop="occurrenceTime">
                    <el-date-picker
                      :disabled="editStatus"
                      v-model="item.occurrenceTime"
                      value-format="YYYY-MM-DD hh:mm:ss"
                      type="date"
                    />
                  </el-form-item>

                  <el-form-item label="上传文档" prop="attachmentArr">
                    <el-upload
                      name="uploadFile"
                      multiple
                      :disabled="editStatus"
                      :accept="acceptTypes"
                      :action="uploadComUrl"
                      :headers="uploadHeaders"
                      :on-success="
                        (response, file, fileList) => {
                          return handleReviewSuccess(
                            response,
                            file,
                            fileList,
                            index
                          );
                        }
                      "
                      :on-remove="
                        (file, fileList) => {
                          return handleReviewRemove(file, fileList, index);
                        }
                      "
                      :on-error="handleError"
                      :file-list="item.files"
                      :before-upload="beforeAvatarUpload"
                      :on-preview="handlePreview"
                    >
                      <el-button
                        size="small"
                        type="primary"
                        :disabled="editStatus"
                        >点击上传</el-button
                      >
                      <template #tip v-if="!editStatus">
                        <div class="el-upload__tip">
                          支持上传doc、docx、xls、xlsx、pdf、ppt、pptx、png、jpg、jpeg等格式文件,文件大小不得大于10M。
                        </div>
                      </template>
                    </el-upload>
                  </el-form-item>

                  <el-form-item label="评审摘要" prop="summary">
                    <el-input
                      :disabled="editStatus"
                      v-model="item.summary"
                      type="textarea"
                    />
                  </el-form-item>

                  <el-form-item label="备注" prop="remark">
                    <el-input
                      :disabled="editStatus"
                      v-model="item.remark"
                      type="textarea"
                    />
                  </el-form-item>
                </el-form>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane name="2" label="添加文档">
        <el-button
          v-if="!editStatus"
          class="btnClass"
          @click="addDoc"
          type="primary"
          >添加文档</el-button
        >
        <el-table
          :data="model.docList"
          border
          style="width: 100%"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
        >
          <el-table-column prop="billNum" label="文档编号" width="180">
          </el-table-column>
          <el-table-column prop="documentName" label="文档名称">
          </el-table-column>
          <el-table-column prop="remarks" label="描述"> </el-table-column>
          <el-table-column prop="projectName" label="所属项目">
          </el-table-column>
          <el-table-column prop="createUserName" label="创建人">
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" min-width="100">
          </el-table-column>
          <el-table-column prop="documentTypeName" label="文档类型">
          </el-table-column>
          <el-table-column prop="projectPhaseName" label="项目阶段">
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="140">
            <template #default="{ row }">
              <el-button
                :disabled="editStatus"
                type="text"
                size="small"
                @click="handleDocEdit(row)"
                >编辑</el-button
              >
              <el-popconfirm
                confirm-button-text="确定"
                cancel-button-text="取消"
                icon="el-icon-info"
                icon-color="red"
                title="确定删除该条记录吗？"
                @confirm="handleDocDelete(row)"
              >
                <template #reference>
                  <el-button
                    :disabled="editStatus"
                    type="text"
                    v-auth="`/document/manage--delete`"
                    >删除</el-button
                  >
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane name="3" label="维护项目编码">
        <el-row>
          <el-col :span="22">
            <el-col :span="4"> 项目编号：</el-col>
            <el-col :span="12">
              <el-input
                :disabled="editStatus"
                v-model.trim="model.projectCode"
                class="width-custom"
              ></el-input>
            </el-col>
            <el-col :span="4">
              <!-- && stageStatus === '2'" -->
              <el-button
                v-if="!editStatus"
                style="margin-left: 20px"
                type="primary"
                @click="saveProjectNumber"
                >保存</el-button
              >
            </el-col>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>

    <div class="footer">
      <el-button
        v-if="!editStatus && stageStatus === '2'"
        type="primary"
        @click="handleSubmit"
        >下一步</el-button
      >
    </div>
    <el-dialog v-model="model.dialogVisible" title="添加文档" width="30%">
      <el-form
        ref="formdocRef"
        @submit.prevent
        :model="model.formState"
        :rules="Rules"
        label-width="120px"
      >
        <el-form-item
          label="文档名称"
          placeholder="请输入文档名称"
          prop="documentName"
        >
          <el-input
            v-model="model.formState.documentName"
            class="width-custom220"
          />
        </el-form-item>

        <el-form-item label="上传文档" prop="documentAttachmentArr">
          <el-upload
            name="uploadFile"
            multiple
            :accept="acceptTypes"
            :action="uploadComUrl"
            :headers="uploadHeaders"
            :on-success="handleSuccess"
            :on-remove="handleRemove"
            :on-error="handleError"
            :file-list="model.formState.files"
            :before-upload="beforeAvatarUpload"
            :on-preview="handlePreview"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持上传doc、docx、xls、xlsx、pdf、ppt、pptx、png、jpg、jpeg等格式文件,文件大小不得大于10M。
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="描述">
          <el-input
            v-model="model.formState.remarks"
            type="textarea"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-row justify="end">
        <el-button @click="model.dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleDocSubmit">确 定</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, unref } from "vue";
import SelectForTable from "/@/components/selectForTable/index.vue";
import * as api from "/@/api/meet";
import * as docApi from "/@/api/document";
import NotifMessage from "/@/utils/message/notification";
import { useRoute, useRouter } from "vue-router";

import { useUpload } from "/@/hooks";
import { postProjectUpdate, updateProjectNumber } from "/@/api/project";

// const { handleDownload } = useUpload();

const props = defineProps({
  projectInfo: {
    type: Object
  }
});
const router = useRouter();

const formRef = ref<HTMLFormElement | null>(null) as any;
const formdocRef = ref<HTMLFormElement | null>(null) as any;

const route = useRoute();
let selectTable = ref([]);
let editStatus = ref(false);
const mode = route.query.mode;
const stageStatus = (props as any).projectInfo.stageStatus;
let model = reactive({
  projectCode: "",
  activeName: "1",
  dataList: [],
  docList: [],
  kyReviewExpertList: [],
  dialogVisible: false,
  docType: "add",
  docIndex: 0,
  formState: {
    documentName: "",
    files: [],
    remarks: "",
    documentAttachmentArr: []
  }
});

onMounted(async () => {
  model.projectCode = props.projectInfo.projectCode;
  if (mode === "edit") {
    editStatus.value = false;
    if (props.projectInfo.saveStatus === "2") {
      editStatus.value = true;
    }
  } else {
    editStatus.value = true;
  }
  await getReviewList();
  await getDocList();
});

const saveProjectNumber = async () => {
  const { code } = await updateProjectNumber(
    props.projectInfo.id,
    model.projectCode
  );
  if (code === 200) {
    NotifMessage.success("保存成功");
    const { fullPath, query } = unref(route);
    router.replace({
      path: "/redirect" + fullPath,
      query: query
    });
  }
};

const getDocList = async () => {
  try {
    const { code, data } = await docApi.getList({
      projectManageId: props.projectInfo.id,
      authItems: [
        {
          itemId: props.projectInfo.id,
          itemName: props.projectInfo.projectName,
          itemType: 3,
          operType: "R"
        },
        {
          itemId: props.projectInfo.id,
          itemName: props.projectInfo.projectName,
          itemType: 3,
          operType: "D"
        }
      ],
      projectPhaseCode: "2",
      pageNum: 1,
      pageSize: 10000
    });
    if (code === 200) {
      model.docList = data.list;
    }
  } catch (err) {
    console.log(err);
  }
};
const getReviewList = async () => {
  const { code, data } = await api.postMeetList2({
    projectId: props.projectInfo.id,
    projectStage: "2",
    pageNum: 1,
    pageSize: 10000
  });
  if (code === 200) {
    model.dataList = data.reverse();
    model.dataList.map(el => {
      el.attachmentArr.map(file => {
        file["name"] = file.fileName;
      });
      el.files = el.attachmentArr;
      // el["participant"] = el.participantList.map(el => el.userId);
    });
    if (model.dataList.length === 0 && !editStatus.value) {
      addReview();
    }
  }
};
const handleSubmit = async () => {
  try {
    const promiseList = [];
    reviewForm.value.map(el => {
      if (el) {
        promiseList.push(new Promise(resolve => el.validate(resolve)));
      }
    });
    let isFlag = true;
    if (promiseList.length !== 0) {
      const flagList = await Promise.all(promiseList);
      isFlag = flagList.filter(el => el === true).length === promiseList.length;
    }
    if (isFlag) {
      if (model.dataList.length > 0) {
        const filter = model.dataList.filter(el => el.id == null);
        if (filter.length > 0) {
          const str = filter.map(el => el.title).join(",");
          NotifMessage.warning(`请先保存主题为：${str},再进行下一步操作`);
          return;
        }
      }
      const copyFormData = {
        id: props.projectInfo.id,
        clickStage: 2
      };
      const { code, message } = await postProjectUpdate(copyFormData);
      if (code === 200) {
        NotifMessage.success("保存成功");
        const { fullPath, query } = unref(route);
        router.replace({
          path: "/redirect" + fullPath,
          query: query
        });
      } else {
        NotifMessage.error(message);
      }
    }
  } catch (err) {
    console.log(err);
  }
};

const changeParticipant = (item, index) => {
  model.dataList[index].participant = item;
};

const reviewForm = ref([]);
const reviewFormRules = ref({
  title: [{ required: true, message: "请输入阶段名称", trigger: "change" }],
  occurrenceTime: [
    { required: true, message: "请选择会议时间", trigger: "change" }
  ],
  // summary: [{ required: true, message: "请输入研究内容", trigger: "change" }],
  attachmentArr: [{ required: true, message: "请上传文档", trigger: "change" }],
  participant: [{ required: true, message: "请选择参评人", trigger: "change" }]
});
const Rules = ref({
  documentName: [
    { required: true, message: "请输入文档名称", trigger: "change" }
  ],
  documentAttachmentArr: [
    { required: true, message: "请上传文档", trigger: "change" }
  ]
});

const {
  handleError,
  beforeAvatarUpload,
  uploadComUrl,
  acceptTypes,
  uploadHeaders
} = useUpload();

const handleReviewSuccess = (res, file, fileList, index) => {
  if (res.code === 200) {
    model.dataList[index].files = fileList;
    model.dataList[index].attachmentArr.push(res.data);
  }
};
const handleReviewRemove = (file, fileList, index) => {
  model.dataList[index].files = fileList;
  model.dataList[index].attachmentArr = model.dataList[
    index
  ].attachmentArr.filter(item => {
    const uuid = file.response ? file.response.data.uuidFile : file.uuidFile;
    return item.uuidFile !== uuid;
  });
};

const handleSuccess = (res, file, fileList) => {
  if (res.code === 200) {
    model.formState.files = fileList;
    model.formState.documentAttachmentArr.push(res.data);
  }
  formRef.value.clearValidate();
};

const handleRemove = (file, fileList) => {
  model.formState.files = fileList;
  model.formState.documentAttachmentArr =
    model.formState.documentAttachmentArr.filter(item => {
      const uuid = file.response ? file.response.data.uuidFile : file.uuidFile;
      return item.uuidFile !== uuid;
    });
};

const handlePreview = (item: any) => {
  window.open(
    `${location.origin}${location.pathname}#/online?uuidFile=${item?.response.data.uuidFile}&fileName=${item?.response.data.fileName}`
  );
};

const addReview = () => {
  model.dataList.push({
    title: "",
    occurrenceTime: "",
    summary: "",
    remark: "",
    attachmentArr: [],
    participant: []
  });
};
const saveReview = async index => {
  const isvaild = await reviewForm.value[index].validate();
  if (isvaild) {
    const parList = selectTable.value[index].participantList;
    const copyFormData = JSON.parse(JSON.stringify(model.dataList[index]));
    copyFormData["projectId"] = props.projectInfo.id;
    copyFormData["projectStage"] = "2";
    copyFormData["participantList"] = parList.map(el => {
      return { userId: el.id, userName: el.userName, name: el.name };
    });

    if (copyFormData.id) {
      const { code, message } = await api.postMeetUpdate(
        Object.assign(copyFormData)
      );
      if (code === 200) {
        NotifMessage.success("修改成功");
      } else {
        NotifMessage.error(message);
      }
    } else {
      const { code, message } = await api.postMeetAdd(copyFormData);
      if (code === 200) {
        NotifMessage.success("保存成功");
        getReviewList();
      } else {
        NotifMessage.error(message);
      }
    }
  }
};

const delForList = async (index: number) => {
  if (model.dataList.length === 1) {
    NotifMessage.warning("立项阶段必须包含至少一个会议评审");
    return;
  }
  try {
    const row = model.dataList[index];
    if (row.id) {
      const { code, message } = await api.postMeetDelete({
        id: row.id
      });
      if (code === 200) {
        model.dataList.splice(index, 1);
        NotifMessage.success("删除成功");
      } else {
        NotifMessage.error(message);
      }
    } else {
      model.dataList.splice(index, 1);
    }
  } catch (err) {
    console.log(err);
  }
};

const handleDocEdit = row => {
  model.docType = "edit";
  model.dialogVisible = true;
  model.formState = JSON.parse(JSON.stringify(row));
  model.formState.documentAttachmentArr.map(el => {
    el["name"] = el.fileName;
  });
  model.formState.files = model.formState.documentAttachmentArr;
};

const addDoc = () => {
  model.docType = "add";
  model.dialogVisible = true;
  model.formState = {
    documentName: "",
    files: [],
    remarks: "",
    documentAttachmentArr: []
  };
};

const handleDocDelete = async row => {
  try {
    const { code, message } = await docApi.onDelete({
      id: row.id
    });
    if (code === 200) {
      NotifMessage.success("删除成功");
      getDocList();
    } else {
      NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
  }
};

const handleDocSubmit = () => {
  console.log(props);
  formdocRef.value.validate(async (valid: any) => {
    if (valid) {
      const copyFormData = JSON.parse(JSON.stringify(model.formState));
      copyFormData.documentTypeName = "项目文件";
      copyFormData.documentTypeCode = "1";

      copyFormData.projectPhaseName = "立项";
      copyFormData.projectPhaseCode = "2";

      copyFormData.projectName = props.projectInfo.projectName;
      copyFormData.projectManageId = props.projectInfo.id;
      copyFormData["authItems"] = [
        {
          itemId: props.projectInfo.id,
          itemName: props.projectInfo.projectName,
          itemType: 3,
          operType: "R"
        },
        {
          itemId: props.projectInfo.id,
          itemName: props.projectInfo.projectName,
          itemType: 3,
          operType: "D"
        }
      ];
      if (model.docType === "add") {
        const { code, message } = await docApi.onAdd(copyFormData);
        // model.docList.push(copyFormData);
        if (code === 200) {
          NotifMessage.success("保存成功");
        } else {
          NotifMessage.error(message);
        }
      } else {
        const { code, message } = await docApi.onSave(copyFormData);
        if (code === 200) {
          NotifMessage.success("修改成功");
        } else {
          NotifMessage.error(message);
        }
      }
      getDocList();
      model.dialogVisible = false;
    } else {
      return false;
    }
  });
};
</script>

<style lang="scss" scoped>
.footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin: 20px 0;
}
.btnClass {
  margin-bottom: 8px;
}
.milepost-box {
  border: 1px solid #d8dce6;
  .milepost-title {
    position: relative;
    height: 40px;
    line-height: 40px;
    font-size: 14px;
    background: #4f9dff0c;
    text-indent: 16px;
    margin-bottom: 20px;
    .close {
      position: absolute;
      right: 20px;
      top: 12px;
      color: red;
      cursor: pointer;
      font-size: 16px;
    }
    .save {
      position: absolute;
      right: 50px;
      top: 12px;
      color: #f89c34;
      cursor: pointer;
      font-size: 16px;
    }
  }
}
</style>
